public class MergeSolution {
	
	public static void MergeWithParent(solution[] solutions)
	{
		//Filtered Id list from trigger
		List<id> solutionIdlist = new list <id>();
		Map<id,id> solutionParentMap = new Map <id,id>();
		for(integer x = 0; x < solutions.size(); x++)
		{
			if(solutions[x].solution_parent__c != null)if(solutions[x].merge_with_parent__c == true)
			{
				solutionIdList.add(solutions[x].Id);
				solutionParentMap.put(solutions[x].Id,solutions[x].solution_parent__c);
			}
		}
		if (solutionParentMap.isempty()==false)
		{
			list<caseSolution> deleteCaseSolutions = new list <casesolution>();
			list<id> caseIdList = new list <id>();
			//Solution Id's that correspond to cases in the case Id List. Using their list index, 
			//we can match them to the correct case.
			list<id> solutionIdList2 = new list <id>();
			for (CaseSolution cs :[select caseId,solutionId from casesolution where solutionId in :solutionIdList])
			{
				caseIdList.add(cs.caseId);
				solutionIdList2.add(cs.solutionId);
				deleteCaseSolutions.add(cs);
			}
			delete deleteCaseSolutions;
			
			CaseSolution[] CreateCaseSolutions = new CaseSolution[]{};
			for(integer x = 0; x < caseIdList.size(); x++)
			{
				CaseSolution cs = new CaseSolution(CaseId=caseIdList[x],SolutionId=solutionParentMap.get(SolutionIdList2[x]));
            	createCaseSolutions.add(cs);
			}
			insert createCaseSolutions;
			
			list<Solution> deleteSolutions = new list <Solution>();			
			for (solution s :[select Id from solution where Id in :solutionIdList])
			{
				deleteSolutions.add(s);
			}
			delete deleteSolutions;
		}			
	}
}